# mongoRepository.coffee
mongodb = require('mongodb')
{RepositoryValue} = require ('./RepositoryValue')
class MongoRepository
  constructor: (@mongoServerName, @databaseName, @collectionName) ->
  @collection = null
  getMongoCollection: (callback) ->
    error = new Error()
    if (not @mongoServerName?)
      error.message = 'mongoServerName cannot be null'
      return callback error
    if (not @databaseName?)
      error.message = 'database cannot be null'
      return callback error
    if (not @collectionName?)
      error.message = 'collectionName cannot be null'
      return callback error
    if (not @collection?)
      mongoServer = new mongodb.Server @mongoServerName, mongodb.Connection.DEFAULT_PORT, {}

      db = new mongodb.Db @databaseName, mongoServer, {}

      db.open (err, client) =>
        if (err)
          return callback(err)
        collection = new mongodb.Collection client, @collectionName
        @collection = collection
        callback(err, @collection)
        @collection
    else
      callback(null, @collection)

  set: (key, value, callback) ->
    if key is null
      error = new Error()
      error.message = 'Key cannot be null'
      return callback error
    @getMongoCollection (err, collection)->
      if not err
        repoValue = new RepositoryValue()
        repoValue._id = key
        repoValue.Value = value
        collection.save repoValue, {safe: true}, callback
      else
        error = new Error()
        error.message = 'could not open collection'
        return callback error

  get: (key, callback) ->
    @getMongoCollection (err, collection)->
      if not err
        collection.findOne {_id: key}, (err, document) ->
          if document?
            callback(err, document.Value)
          else
            callback(err, null)
      else
        callback(err)

  remove: (key, callback) ->
    @getMongoCollection (err, collection) ->
      if not err
        collection.remove {_id: key}, {safe: true}, (err, numberOfRemovedDocuments) ->
          callback(err, numberOfRemovedDocuments)
      else
        callback(err)

  contains: (key, callback) ->
    @get key, (err, value) ->
      if not err
        if (value isnt null)
          callback(err, true)
        else
          callback(err, true)
      else
        callback(err)

root = exports ? window
root.MongoRepository = MongoRepository